package com.yoomiito.app.ui.fragment

import android.content.Context
import android.content.Intent
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.android.material.appbar.AppBarLayout
import com.gyf.barlibrary.ImmersionBar
import com.yoomiito.app.Constant
import com.yoomiito.app.ImmersionBarFragment
import com.yoomiito.app.R
import com.yoomiito.app.adapter.goods.list.sort.StarStoreGoodsAdapter
import com.yoomiito.app.adapter.goods.list.sort.ThemeBaoPinGoodsAdapter
import com.yoomiito.app.adapter.goods.list.sort.ThemeYouPinGoodsAdapter
import com.yoomiito.app.base.App
import com.yoomiito.app.model.gift.GiftGoods
import com.yoomiito.app.model.gift.GiftGoodsList
import com.yoomiito.app.model.gift.GiftType
import com.yoomiito.app.ui.goods.NewGoodsInfoActivity
import com.yoomiito.app.ui.my.car.ShopCarActivity
import com.yoomiito.app.utils.*
import com.yoomiito.app.widget.SpacingDecoration
import com.yoomiito.app.widget.state.ContentType
import com.yoomiito.app.widget.state.EmptyType
import com.yoomiito.app.widget.state.StatusManager
import kotlinx.android.synthetic.main.act_goods_sort.*
import kotlinx.android.synthetic.main.act_youpin_goods.frameLayout
import kotlinx.android.synthetic.main.fm_rcy.*
import kotlinx.android.synthetic.main.fragment_goods_sort.goShopCar
import kotlinx.android.synthetic.main.fragment_goods_sort.tv_card_num
import kotlinx.android.synthetic.main.icon_shop_car.*
import kotlin.math.abs

/**
 * 优品专区
 * 爆品专区
 * 淘宝专区
 * 带顶部主图的列表
 */
class GoodsSortListFragment : ImmersionBarFragment<GoodsSortListPresenter>() {

    private var mGoodsType: Int = AllCode.YouPin//初始化
    private lateinit var mAdapter: BaseQuickAdapter<GiftGoods, BaseViewHolder>
    private var mCurrentPage: Int = 1
    private var mSort: Int = 0//排序
    private var mType: Long = 3 //商品类型
    private var mGoodsTypeToData: Int = 3
    private var salesSort: Int = 0//排序
    private var categorizeId: Int = 0//

    public override fun initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.color_FF035B)
                .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
                //                .navigationBarDarkIcon(true) //导航栏图标是深色，不写默认为亮色
                .fitsSystemWindows(true) //                .statusBarColor(R.color.colorPrimary)
                //                .statusBarDarkFont(true)
                //                .navigationBarColor(R.color.colorPrimary)
                .init()
    }

    override fun getLayoutId(): Int = R.layout.fragment_goods_sort

    override fun newP(): GoodsSortListPresenter = GoodsSortListPresenter(App.mAppConfig)

    companion object {
        fun start(context: Context, title: String, type: Int) {
            val intent = Intent(context, GoodsSortListFragment::class.java)
            intent.putExtra(Constant.DATA, title)
            intent.putExtra(Constant.TYPE, type)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

    override fun initData(savedInstanceState: Bundle?) {


        mGoodsTypeToData = when (mGoodsType) {
            AllCode.BaoPin -> 2
            AllCode.YouPin -> 3
            AllCode.AgentMall -> 4
            AllCode.StarStore -> 5//星店
            else -> {
                YMToast.showText("数据异常")
                0
            }
        }
//        when (mGoodsType) {
//            AllCode.BaoPin -> {
//                shopCarLl.visibility = View.VISIBLE
//                shopCar.visibility = View.VISIBLE
//                shopCarLl.setOnClickListener {
//                    if (App.mAppConfig.isLogin) {
//                        ShopCarActivity.start(context)
//                    } else {
////                        AllUtils.toLogin(this, AllCode.LoginIn)
//                        AllUtils.toLogin(context, AllCode.LoginIn)
//
//                    }
//                }
//            }
//            AllCode.YouPin -> {
//                shopCar.visibility = View.GONE
//                shopCarLl.visibility = View.VISIBLE
//                searchIv.visibility = View.VISIBLE
//                searchIv.setOnClickListener { YouPinSearchActivity.start(context) }
//            }
//        }
//        initAppbarLayout()
        initTabView()
        initStatusView()
        initRefresh()
        initRcy()
        showNewFlag(false)
        showLoading()
        p.getGoodsType(mGoodsTypeToData)
        requestData()
        goShopCar.setOnClickListener {
            if (App.mAppConfig.isLogin) {
                ShopCarActivity.start(context)
            } else {
//                        AllUtils.toLogin(YouPinGoodsActivity.this,AllCode.LoginIn);
                LoginUtils.toOneKeyLogin(context)
            }
        }
    }

    private fun initAppbarLayout() {
        appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, i ->
            when {
                i == 0 -> {//展开
                    toolbarLl.setBackgroundResource(R.color.color_tran)
                    titleTv.visibility = View.INVISIBLE
                    val d = show_new.background as GradientDrawable
                    d.setColor(ResUtil.getColor(R.color.color_FF035B))
                }

                abs(i) >= appBarLayout.totalScrollRange -> {//折叠
                    toolbarLl.background = ColorUtils.gradient("#FFFF246C", "#FFFF035B")
                    titleTv.visibility = View.VISIBLE
                    val d = show_new.background as GradientDrawable
                    d.setColor(ResUtil.getColor(R.color.color_tran))
                }

                else -> {//中间
                    toolbarLl.setBackgroundResource(R.color.color_tran)
                    titleTv.visibility = View.INVISIBLE
//                    if (abs(i)>=appBarLayout.totalScrollRange/2){
//                        appBarLayout.setExpanded(false,true)
//                    }else{
//                        appBarLayout.setExpanded(true,true)
//                    }
                }
            }
        })
    }


    /**
     *
     */
    private fun requestData() {
        p.getCarNum();
//        p.getGoodsList(mSort, mCurrentPage, mType, mGoodsTypeToData)
        p.getGoodsList(mSort, mCurrentPage, mType, categorizeId, salesSort)

    }

    override fun onStart() {
        super.onStart()
        if (mGoodsType == AllCode.BaoPin && App.mAppConfig.isLogin) {
            p.getList(1)
        }
    }

    private fun initTabView() {
        tabView.setDownName("_des")
                .setUpName("_asc")
                .setPriceFirstName("sale_price")
                .setSaleFirstName("volume")
                .showSort()
                .setDefault()

        tabView.setOnChangeListener { sort, salesSort, _ ->
            mSort = sort
            this.salesSort = salesSort
            mCurrentPage = 1
            requestData()
        }

        tabView.setOnSortClickListener { giftType ->
            mCurrentPage = 1
            categorizeId = giftType.id.toInt()
            showLoading()
            requestData()
        }

    }

    private fun initStatusView() {
        mStatusManager = StatusManager.Builder(context)
                .addType(ContentType(R.layout.fm_rcy))
                .addType(EmptyType().setEmptyContent("暂无商品"))
                .build()
        frameLayout.addView(mStatusManager.view())
    }

    private fun initRefresh() {
        fm_refreshLayout.setOnRefreshListener {
            mCurrentPage = 1
            requestData()
        }

        fm_refreshLayout.setOnLoadMoreListener {
            mCurrentPage++
            requestData()
        }
    }

    private fun initRcy() {
        fm_rcy.setBackgroundResource(R.color.color_F4F4F4)
        fm_rcy.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
        val sd = SpacingDecoration(DensityUtil.dp2px(10f), DensityUtil.dp2px(10f), true)
        fm_rcy.addItemDecoration(sd)

        when (mGoodsType) {
            AllCode.YouPin -> {
                mAdapter = ThemeYouPinGoodsAdapter(null)//优品
            }

            AllCode.BaoPin -> {
                mAdapter = ThemeBaoPinGoodsAdapter(null)
//                val view = LayoutInflater.from(this).inflate(R.layout.icon_shop_car, null)
//                view.setOnClickListener {
//                    if (App.mAppConfig.isLogin) {
//                        ShopCarActivity.start(this)
//                    } else {
//                        AllUtils.toLogin(this, AllCode.LoginIn)
//                    }
//                }
//                val lp = FrameLayout.LayoutParams(DensityUtil.dp2px(48f), DensityUtil.dp2px(48f))
//                lp.bottomMargin = DensityUtil.dp2px(12f)
//                lp.rightMargin = DensityUtil.dp2px(12f)
//                lp.gravity = Gravity.RIGHT or Gravity.BOTTOM
//                frameLayout.addView(view, lp)
            }//爆品
            AllCode.AgentMall -> mAdapter = ThemeYouPinGoodsAdapter(null)//区代商城
            AllCode.StarStore -> {
                fm_rcy.removeItemDecoration(sd)
                fm_rcy.addItemDecoration(SpacingDecoration(DensityUtil.dp2px(12f), DensityUtil.dp2px(10f), true))
                mAdapter = StarStoreGoodsAdapter(null)

            }//星店商城
        }
        fm_rcy.adapter = mAdapter
        mAdapter?.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            var info = mAdapter.data[position]
            NewGoodsInfoActivity.toGoodsInfo(context, info.id.toString(), "2")
        }
    }

    fun showGift(goodsList: GiftGoodsList) {
        val data = goodsList.data
        if (mCurrentPage == 1) {
            if (data == null || data.size == 0) {
                mStatusManager.showEmpty()
            } else {
                mStatusManager.showContent()
                mAdapter.setNewData(data)
            }
            fm_refreshLayout.finishRefresh(true)
            fm_refreshLayout.setNoMoreData(false)
        } else {
            fm_refreshLayout.finishLoadMore(true)
            if (data == null || data.size == 0) {
                Toast.makeText(context, "没有更多了", Toast.LENGTH_SHORT).show()
                fm_refreshLayout.finishLoadMoreWithNoMoreData()
            } else {
                mAdapter.addData(data)
            }
        }

    }

    fun showCar(goodsList: GiftGoodsList){
        if(tv_card_num!= null ){
            if(goodsList.cartNum == 0){
                tv_card_num.visibility = LinearLayout.GONE
            }else{
                tv_card_num.visibility = LinearLayout.VISIBLE
                tv_card_num.text = "" + goodsList.cartNum
            }
        }
    }

    fun setType(types: MutableList<GiftType>?) {
        if (types != null) {
            types.add(0, GiftType(0, "全部", true))
            tabView.setGiftTypes(types)
        }
    }

    fun showNewFlag(show: Boolean) {
        show_new.visibility = if (show) View.VISIBLE else View.GONE
    }

    override fun eventMessage(eventMessage: EventMessage?) {
        super.eventMessage(eventMessage)
        if (Type.EventMsgType.LoginSuccess == eventMessage?.eventType || Type.EventMsgType.LoginOut == eventMessage?.eventType || AllCode.NotifyShopCarData == eventMessage?.eventType) {
            mCurrentPage = 1
            p.getCarNum()
        }

    }
}